import { createRouter, createWebHashHistory } from 'vue-router'
import { markRaw } from 'vue'

import { useSystemStore } from '@/stores/system'
import { BASE_REDIRECT_PATH, TOKEN_KEY } from '@/constants'

import NProgress from 'nprogress'
import { nanoid } from 'nanoid'

const Login = () => import('@/views/login/index.vue')
const NotFound = () => import('@/views/notFound/index.vue')
const Layout = () => import('@/layout/index.vue')

export const constantRoutes = [
    {
        path: '/',
        redirect: BASE_REDIRECT_PATH
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound
    }
]

export const layoutRoute = {
    path: '/layout',
    name: Symbol('Layout'),
    component: markRaw(Layout)
}

export const defaultNavItem = `defaultNavItem`
export const defaultNavList = [
    {
        kid: nanoid(),
        subSystemType: defaultNavItem,
        url: '/home',
        sysName: '首页',
        name: 'Home',
        visible: true,
        component: () => import('@/views/home/index.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes: [
        ...constantRoutes,
        layoutRoute
    ]
})

export default router

const whiteList = ['/login']

router.beforeEach(async (to, form) => {
    const { token, username, password } = to.query
    if (token) {
        const systemStore = useSystemStore()
        systemStore.$reset()
        localStorage.setItem(TOKEN_KEY, token)
    } else if (username && password) {
        try {
            const formData = { username, password }
            const systemStore = useSystemStore()
            systemStore.$reset()
            await systemStore.login(formData)
            if (to.path.startsWith('/login')) {
                return BASE_REDIRECT_PATH
            }
        } catch (error) {
            defaultCatchError(error)
            localStorage.removeItem(TOKEN_KEY)
            return { path: `/login`, replace: true }
        }
    }
})

router.beforeEach(async (to, from) => {
    const systemStore = useSystemStore()
    const hasToken = localStorage.getItem(TOKEN_KEY)
    NProgress.start()
    if (hasToken) {
        if (to.path === '/login') {
            return true
        } else {
            if (!systemStore.loginFlag) {
                try {
                    await systemStore.initPermission() // 权限
                    return { path: to.path }
                } catch (error) {
                    defaultCatchError(error)
                    return { path: `/login`, replace: true }
                }
            } else {
                return true
            }
        }
    } else {
        if (whiteList.includes(to.path)) {
            return true
        } else {
            return { path: `/login`, replace: true }
        }
    }
})

router.afterEach((to, from) => {
    NProgress.done()
})